package controllers;

import helpers.UrlHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import systems.ConfigSystem;

import debugs.CheckSpeedDebug;

import entities.CheckSpeed;
import entities.SiteConfig;

import models.CheckSpeedModel;

public class CheckSpeedServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		String name = (String) request.getParameter("domain");
		String result = "";
		
		if (name == null || !UrlHelper.checkDomain(name)) {
			check.put("name", "Please provice your domain.");
		} else {
			name = UrlHelper.getMainDomain(name);
		} 
		
		CheckSpeedModel checkSpeedModel = CheckSpeedModel.getInstance();
		CheckSpeed checkSpeed = null;
		
		if (check.size() == 0) {
			checkSpeed = checkSpeedModel.get(name);
			if (checkSpeed == null) {
				checkSpeed = new CheckSpeed();
				checkSpeed.setDomain(name);
				checkSpeed.setProcessing(true);
			} else {
				CheckSpeedDebug.debug(checkSpeed);
			}
			
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("check", check);
		request.setAttribute("name", name);
		request.setAttribute("checkSpeed", checkSpeed);
		try {
			request.getRequestDispatcher("/pages/check_speed.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
